#!/usr/bin/python
# -*- coding: UTF-8 -*-

from monitor.base import MonitorBase
from utils.log.log import Log
from utils.smtp.smtp import Smtp
import psutil as p
from config.config import (
    COMMON_INTERVALTIME,
    ALARM_MEM_PERCENTAGE_LIMIT,
    ALARM_MEM_EXCEPT_MAX_NUM,
)
from utils.utils import bytes2human
from utils.utils import (
    get_host_ip,
    get_host_name,
)

log = Log("mem monitor")


class MemMonitor(MonitorBase):
    """docstring for MemMonitor"""

    def __init__(self):
        super(MemMonitor, self).__init__(COMMON_INTERVALTIME)
        self.smtp = None
        self.num = 0

    def Init(self):
        """Init(self)"""
        log.Debug("mem monitor init")
        self.smtp = Smtp()
        self.num = 0

    def Check(self):
        """Check(self)"""
        log.Debug("mem monitor Check !!!!")
        m = p.virtual_memory()
        log.Debug(
            "mem info=",
            "total=%s used=%s free=%s per=%f"
            % (
                bytes2human(m.total),
                bytes2human(m.used),
                bytes2human(m.free),
                m.percent,
            ),
        )
        if m.percent >= ALARM_MEM_PERCENTAGE_LIMIT:
            self.num = self.num + 1
            log.Debug(
                "mem_percent except appear %d times and max ALARM_MEM_EXCEPT_MAX_NUM times=%d"
                % (self.num, ALARM_MEM_EXCEPT_MAX_NUM)
            )
            if self.num >= ALARM_MEM_EXCEPT_MAX_NUM:
                log.Debug("mem_percents=", m.percent)
                self.smtp.Send(
                    "server %s[%s] appear mem percentage limit max!!!!!!!!!!!!!!!!!!"
                    % (get_host_ip(), get_host_name())
                )
                self.num = 0
        else:
            self.num = 0
